import json
import subprocess
import sys
from datetime import datetime


class AIPackageValidator:
    def __init__(self, test_cases_dir="test_cases"):
        self.results = []
        self.test_cases_dir = test_cases_dir

    def install_package(self, package_name):
        """安装PyPI包"""
        try:
            subprocess.run([
                sys.executable, "-m", "pip", "install", package_name
            ], check=True, capture_output=True, text=True)
            return True, None
        except subprocess.CalledProcessError as e:
            return False, e.stderr

    def run_test(self, package_name, test_script):
        """执行测试用例"""
        try:
            result = subprocess.run([
                sys.executable, "-c", test_script
            ], capture_output=True, text=True, timeout=30)

            return {
                "package": package_name,
                "status": "PASS" if result.returncode == 0 else "FAIL",
                "stdout": result.stdout,
                "stderr": result.stderr,
                "timestamp": datetime.now().isoformat()
            }
        except subprocess.TimeoutExpired:
            return {
                "package": package_name,
                "status": "TIMEOUT",
                "error": "Test execution timeout",
                "timestamp": datetime.now().isoformat()
            }

    def validate_package(self, package_name, test_script):
        """完整验证流程"""
        print(f"🔍 Validating {package_name}...")

        # 安装测试
        install_success, install_error = self.install_package(package_name)
        if not install_success:
            return {
                "package": package_name,
                "status": "INSTALL_FAIL",
                "error": install_error,
                "timestamp": datetime.now().isoformat()
            }

        # 功能测试
        test_result = self.run_test(package_name, test_script)
        self.results.append(test_result)
        return test_result

    def save_results(self, output_file="validation_results.json"):
        """保存验证结果"""
        with open(output_file, 'w') as f:
            json.dump(self.results, f, indent=2, ensure_ascii=False)
        print(f"📊 Results saved to {output_file}")


# 使用示例
if __name__ == "__main__":
    validator = AIPackageValidator()

    # 测试用例示例
    test_cases = {
        "numpy": "import numpy; print(numpy.array([1,2,3]).sum())",
        "pandas": "import pandas; print(pandas.DataFrame({'a':[1,2,3]}).shape)",
        "torch": "import torch; print(torch.cuda.is_available())"
    }

    for pkg, test in test_cases.items():
        validator.validate_package(pkg, test)

    validator.save_results()